package win.start;

import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.junit.Before;
import org.junit.Test;

/**
 * TODO: 如果连接数量超过了连接池的连接数量，会发生什么？测试一下？
 * Created by 张少昆 on 2017/6/17.
 */
public class ConnPoolingTest2 {
	private PoolingHttpClientConnectionManager cm = null;
	CloseableHttpClient httpclient = null;

	@Before
	public void setUp(){
		cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(256);
		cm.setDefaultMaxPerRoute(32);
		SocketConfig socketConfig = SocketConfig.custom()
				.setSoReuseAddress(true)
				.setSoKeepAlive(true)
				.setSoTimeout(5000)
				.setTcpNoDelay(true)
				.setSoLinger(-1) //http://blog.csdn.net/huang_xw/article/details/7338612
				.build();

		httpclient = HttpClients.custom()
				.setConnectionManager(cm)
				.setDefaultConnectionConfig(null)
				.setDefaultRequestConfig(null)
				.setDefaultSocketConfig(socketConfig)
				.setConnectionTimeToLive(10, null)
				.build();

		// TODO: 我擦，看代码，HttpClients.createDefault()，跟上面这段几乎一样！！！
		CloseableHttpClient aDefault = HttpClients.createDefault();

		// HttpClientBuilder，可以先调用useSystemProperties(),然后再build()，这样：
		// 默认会创建一个PoolingHttpClientConnectionManager
		// 默认使用DefaultClientConnectionReuseStrategy，该策略就是检查请求头Connection，如果有Close，就关闭。
		// 默认使用DefaultConnectionKeepAliveStrategy，该策略就是检查响应头，查找time-out
		// 见下面的代码： --如果不调用useSystemProperties()，貌似无法继续？？抛出错误？
//		if (systemProperties) {
//			String s = System.getProperty("http.keepAlive", "true");
//			if ("true".equalsIgnoreCase(s)) {
//				s = System.getProperty("http.maxConnections", "5");
//				final int max = Integer.parseInt(s);
//				poolingmgr.setDefaultMaxPerRoute(max);
//				poolingmgr.setMaxTotal(2 * max);
//			}
//		}
//		if (maxConnTotal > 0) {
//			poolingmgr.setMaxTotal(maxConnTotal);
//		}
//		if (maxConnPerRoute > 0) {
//			poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
//		}
	}

	/**
	 * 搞错了，HttpClient相当于一个浏览器，不应该出现多个浏览器 -- 效率太低下。
	 * 这里就权作测试用吧。
	 */
	@Test
	public void r1(){
		CloseableHttpClient httpclient1 = HttpClients.custom()
				.setConnectionManager(cm)
				.build();
		CloseableHttpClient httpclient2 = HttpClients.custom()
				.setConnectionManager(cm)
				.build();

		System.out.println(httpclient1 == httpclient2);
	}
}
